package middle;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Solution_3 {
    public int lengthOfLongestSubstring(String s) {
        Set<Character> set = new HashSet<>();
        int left = 0, right = -1, max = 0;
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (set.contains(c)) {
                max = Math.max(max, right - left + 1);
            }
            while (set.contains(c)) {
                set.remove(chars[left]);
                left++;
            }
            right++;
            set.add(c);
        }
        max = Math.max(max, right - left + 1);
        return max;
    }

    public int lengthOfLongestSubstring_1(String s) {
        int maxCount = 0;
        int count = 0, clearIndex = 0;
        int[] arrays = new int[1000];
        for (int i = 0; i < arrays.length; i++) {
            arrays[i] = -1;
        }
//        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (arrays[c] >= 0) {//  map.containsKey(c)
                maxCount = Math.max(maxCount, count);
//                Integer index = map.get(c);
                Integer index = arrays[c];
                count = i - index;
                for (Integer clearI = clearIndex; clearI < index; clearI++) {
//                    map.remove(s.charAt(clearI));
                    arrays[s.charAt(clearI)] = -1;
                }
                clearIndex = index + 1;
            } else {
                count++;
            }
//            map.put(c, i);
            arrays[c] = i;
        }
        return Math.max(maxCount, count);
    }

    public static void main(String[] args) {
        Solution_3 model = new Solution_3();
        System.out.println(model.lengthOfLongestSubstring("abcabcbb")); // 3
        System.out.println(model.lengthOfLongestSubstring("bbbbb")); // 1
        System.out.println(model.lengthOfLongestSubstring("pwwkew")); // 3
        System.out.println(model.lengthOfLongestSubstring("")); // 0
        System.out.println(model.lengthOfLongestSubstring("tmmzuxt")); // 5
        System.out.println(model.lengthOfLongestSubstring("bbtablud")); // 6
        System.out.println(model.lengthOfLongestSubstring("aabaab!bb"));
    }
}
